<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑订单申请' : '新增订单申请'"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户ID" prop="customerId">
            <el-input-number
              v-model="form.customerId"
              :min="1"
              placeholder="请输入客户ID"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="form.productName" placeholder="请输入产品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品规格" prop="productSpec">
            <el-input v-model="form.productSpec" placeholder="请输入产品规格" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="数量" prop="quantity">
            <el-input-number
              v-model="form.quantity"
              :min="1"
              placeholder="请输入数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单价" prop="unitPrice">
            <el-input-number
              v-model="form.unitPrice"
              :min="0.01"
              :precision="2"
              placeholder="请输入单价"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总金额" prop="totalAmount">
            <el-input-number
              v-model="form.totalAmount"
              :min="0.01"
              :precision="2"
              placeholder="请输入总金额"
              style="width: 100%"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="收货地址" prop="deliveryAddress">
        <el-input
          v-model="form.deliveryAddress"
          type="textarea"
          :rows="2"
          placeholder="请输入收货地址"
        />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="订单描述" prop="orderDescription">
        <el-input
          v-model="form.orderDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入订单描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { createOrder, updateOrder } from '../../api/order.js'

export default {
  name: 'OrderForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    order: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const loading = ref(false)
    
    const form = reactive({
      id: null,
      customerId: null,
      customerName: '',
      productName: '',
      productSpec: '',
      quantity: 1,
      unitPrice: 0.01,
      totalAmount: 0.01,
      deliveryAddress: '',
      contactPerson: '',
      contactPhone: '',
      orderDescription: ''
    })
    
    const rules = {
      customerName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' }
      ],
      customerId: [
        { required: true, message: '请输入客户ID', trigger: 'blur' }
      ],
      productName: [
        { required: true, message: '请输入产品名称', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
      ],
      unitPrice: [
        { required: true, message: '请输入单价', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
      ],
      totalAmount: [
        { required: true, message: '请输入总金额', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '总金额必须大于0', trigger: 'blur' }
      ],
      deliveryAddress: [
        { required: true, message: '请输入收货地址', trigger: 'blur' }
      ],
      contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    }
    
    const isEdit = computed(() => !!props.order?.id)
    const dialogVisible = computed(() => props.visible)
    
    // 计算总金额
    watch([() => form.quantity, () => form.unitPrice], () => {
      form.totalAmount = Number((form.quantity * form.unitPrice).toFixed(2))
    }, { immediate: true })
    
    // 监听对话框显示状态
    watch(() => props.visible, (visible) => {
      if (visible) {
        resetForm()
        if (props.order) {
          Object.assign(form, props.order)
        }
      }
    })
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        id: null,
        customerId: null,
        customerName: '',
        productName: '',
        productSpec: '',
        quantity: 1,
        unitPrice: 0.01,
        totalAmount: 0.01,
        deliveryAddress: '',
        contactPerson: '',
        contactPhone: '',
        orderDescription: ''
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      emit('update:visible', false)
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        const valid = await formRef.value.validate()
        if (!valid) return
        
        loading.value = true
        
        if (isEdit.value) {
          await updateOrder(form.id, form)
          ElMessage.success('订单更新成功')
        } else {
          await createOrder(form)
          ElMessage.success('订单创建成功')
        }
        
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交订单失败:', error)
        ElMessage.error('提交订单失败')
      } finally {
        loading.value = false
      }
    }
    
    return {
      formRef,
      form,
      rules,
      loading,
      isEdit,
      dialogVisible,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
